//
//  PlayerSettingController.m
//  MapEdit
//
//  Created by Steven Canfield on 7/10/07.
//

#import "PlayerSettingController.h"

@implementation PlayerSettingController

static NSArray * playerColors;
static NSArray * raceArray;
static NSArray * controllerArray;

static NSString * PlayerSettingTableViewType = @"PlayerSettingTableViewType";

- (void)awakeFromNib {
	tableViewArray = [[NSArray alloc] initWithObjects:tableView1, tableView2, tableView3, tableView4, NULL];
	randomStartArray = [[NSArray alloc] initWithObjects:randomStart1, randomStart2, randomStart3, randomStart4, NULL];
	alliedArray = [[NSArray alloc] initWithObjects:allied1, allied2, allied3, allied4, NULL];
	alliedVictoryArray = [[NSArray alloc] initWithObjects:alliedVictory1, alliedVictory2, alliedVictory3, alliedVictory4, NULL];
	sharedVisionArray = [[NSArray alloc] initWithObjects:sharedVision1, sharedVision2, sharedVision3, sharedVision4, NULL];
	forceNameArray = [[NSArray alloc] initWithObjects:forceName1, forceName2, forceName3, forceName4, NULL];
	
	playerColors = [[NSArray alloc] initWithObjects:[NSColor redColor], [NSColor blueColor], [NSColor tealColor], [NSColor purpleColor],
													[NSColor orangeColor], [NSColor whiteColor], [NSColor yellowColor], [NSColor greenColor], NULL];
	raceArray = [[NSArray alloc] initWithObjects:@"Zerg", @"Terran", @"Protoss", @"Independent", @"Neutral", @"User Select", @"Inactive", @"Human", NULL];
	controllerArray = [[NSArray alloc] initWithObjects:@"NOT USED", @"", @"", @"Rescuable", @"", @"Computer", @"Human", @"Neutral",  NULL];

    [tableViewArray makeObjectsPerformSelector:@selector(registerForDraggedTypes:) withObject:[NSArray arrayWithObject:PlayerSettingTableViewType]];
}

- (void)reloadAllData {
	int forceIndex;
	for( forceIndex = 0; forceIndex < 4; forceIndex++ ) {
		[[randomStartArray objectAtIndex:forceIndex] setState:[self forceHasRandomStartLocation:forceIndex]];
		[[alliedArray objectAtIndex:forceIndex] setState:[self forceIsAllied:forceIndex]];
		[[alliedVictoryArray objectAtIndex:forceIndex] setState:[self forceHasAlliedVictory:forceIndex]];
		[[sharedVisionArray objectAtIndex:forceIndex] setState:[self forceHasSharedVision:forceIndex]];
		[[forceNameArray objectAtIndex:forceIndex] setStringValue:[stringManager stringAtIndex: force.name[ forceIndex ]]];
	}
	[self initializeForceSets];
	[tableViewArray makeObjectsPerformSelector:@selector(reloadData)];
}

- (void)initializeForceSets {
	if( forceSetArray != NULL ) {
		[forceSetArray release];
	}
	forceSetArray = [[NSMutableArray alloc] init];
	int forceIndex;
	for( forceIndex = 0; forceIndex < 4; forceIndex++ ) {
		[forceSetArray addObject:[NSMutableArray array]];
	}
	
	for( forceIndex = 0; forceIndex < 8; forceIndex++ ) {
		[[forceSetArray objectAtIndex: force.force[ forceIndex ]] addObject:[NSNumber numberWithInt:forceIndex ]];
	}
	
	for( forceIndex = 0; forceIndex < 4; forceIndex++ ) {
		//NSLog(@"%@", [[forceSetArray objectAtIndex: forceIndex ] description]);
	}
}

- (void)loadIOWN:(NSData *)iownData {
	assert( iownData != NULL );
	[iownData getBytes:&playerOwner range:NSMakeRange( 0, sizeof( chk_iown_t ))];
}

- (void)loadOWNR:(NSData *)ownrData {
	assert( ownrData != NULL );
	[ownrData getBytes:&owner range:NSMakeRange( 0, sizeof( chk_ownr_t ))];
}

- (void)loadSIDE:(NSData *)sideData {
	assert( sideData != NULL );
	[sideData getBytes:&side range:NSMakeRange( 0, sizeof( chk_side_t ))];
}

- (void)loadFORC:(NSData *)forcData {
	assert( forcData != NULL );
	[forcData getBytes:&force range:NSMakeRange( 0, sizeof( chk_forc_t ))];
	swap_chk_forc( &force );
	[self initializeForceSets];
}

- (void)loadCOLR:(NSData *)colrData {
	if( colrData != NULL ) {
		[colrData getBytes:&color range:NSMakeRange( 0, sizeof( chk_colr_t ))];
	} else {
		int i;
		for( i = 0; i < 8; i++ ) {
			color.player_color[i] = i;
		}
	}
}

- (NSData *)serializedIOWN {
	NSMutableData * data = [NSMutableData data];
	[data appendSectionNamed:"IOWN" withBytes:&playerOwner length:sizeof( chk_iown_t )];
	return data;
}

- (NSData *)serializedOWNR {
	NSMutableData * data = [[NSMutableData alloc] init];
	[data appendSectionNamed:"OWNR" withBytes:&owner length:sizeof( chk_ownr_t )];
	return data;
}

- (NSData *)serializedSIDE {
	NSMutableData * data = [[NSMutableData alloc] init];
	[data appendSectionNamed:"SIDE" withBytes:&side length:sizeof( chk_side_t )];
	return data;
}

- (NSData *)serializedFORC {
	NSMutableData * data = [[NSMutableData alloc] init];
	[data appendSectionNamed:"FORC" withBytes:&force length:sizeof( chk_forc_t )];
	return data;
}

- (NSData *)serializedCOLR {
	NSMutableData * data = [[NSMutableData alloc] init];
	[data appendSectionNamed:"COLR" withBytes:&color length:sizeof( chk_colr_t )];
	return data;
}

- (BOOL)forceHasRandomStartLocation:(int)forceNumber {
	if( force.flags[ forceNumber ] & 1 ) {
		return YES;
	}
	return NO;
}

- (BOOL)forceIsAllied:(int)forceNumber {
	if( force.flags[ forceNumber ] & 2 ) {
		return YES;
	}
	return NO;
}

- (BOOL)forceHasAlliedVictory:(int)forceNumber {
	if( force.flags[ forceNumber ] & 4 ) {
		return YES;
	}
	return NO;
}

- (BOOL)forceHasSharedVision:(int)forceNumber {
	if( force.flags[ forceNumber ] & 8 ) {
		return YES;
	}
	return NO;
}

- (void)setStringManager:(StringManager *)manager {
	if( manager != stringManager ) {
		[stringManager release];
		stringManager = [manager retain];
	}
}

- (IBAction)propertyChanged:(id)sender {
	
}

- (int)numberOfRowsInTableView:(NSTableView *)tableView
{
	int forceNumber = [tableViewArray indexOfObject:tableView];
	return [[forceSetArray objectAtIndex:forceNumber] count];
}

- (id)tableView:(NSTableView *)tableView
	objectValueForTableColumn:(NSTableColumn *)tableColumn
	row:(int)rowIndex
{
	int forceNumber = [tableViewArray indexOfObject:tableView];
	int playerIndex = [[[forceSetArray objectAtIndex:forceNumber] objectAtIndex:rowIndex] intValue];
	
	if( [[tableColumn identifier] isEqualToString:@"player"] ) {
		return [NSNumber numberWithInt:playerIndex+1];
	} else if( [[tableColumn identifier] isEqualToString:@"race"] ) {
		NSArray * menu = [[NSArray alloc] initWithObjects:@"Zerg", @"Protoss", @"Terran", NULL];
		int race = side.race[ playerIndex ];
		return menu;
		return [raceArray objectAtIndex: race ];
	} else if( [[tableColumn identifier] isEqualToString:@"controller"] ) {
		int controller = owner.players[ playerIndex ];
		return [controllerArray objectAtIndex:controller];
	} else if( [[tableColumn identifier] isEqualToString:@"color"] ) {
		return [self imageCellForPlayerColor: color.player_color[ playerIndex ] ];
	}
	
	return @"EMPTY";
}

- (void)tableView:(NSTableView *)tableView
	setObjectValue:(id)value
	forTableColumn:(NSTableColumn *)tableColumn
	row:(int)rowIndex
{
	return;
}

- (BOOL)tableView:(NSTableView *)tv writeRowsWithIndexes:(NSIndexSet *)rowIndexes toPasteboard:(NSPasteboard*)pboard {
	NSData *data = [NSKeyedArchiver archivedDataWithRootObject:rowIndexes];
    [pboard declareTypes:[NSArray arrayWithObject:PlayerSettingTableViewType] owner:self];
    [pboard setData:data forType:PlayerSettingTableViewType];
    return YES;
}

- (NSDragOperation)tableView:(NSTableView*)tv validateDrop:(id <NSDraggingInfo>)info proposedRow:(int)row proposedDropOperation:(NSTableViewDropOperation)op {
    return NSDragOperationEvery;
}

- (BOOL)tableView:(NSTableView *)aTableView acceptDrop:(id <NSDraggingInfo>)info row:(int)row dropOperation:(NSTableViewDropOperation)operation {
    NSPasteboard* pboard = [info draggingPasteboard];
    NSData* rowData = [pboard dataForType:PlayerSettingTableViewType];
    NSIndexSet* rowIndexes = [NSKeyedUnarchiver unarchiveObjectWithData:rowData];
    int dragRow = [rowIndexes firstIndex];
	int playerIndex = [self playerNumberForTableView:[info draggingSource] rowIndex:dragRow];
	
	NSLog(@"Moving Player %i to Force %i", playerIndex, [tableViewArray indexOfObject: aTableView ] );
	
	force.force[ playerIndex ] = [tableViewArray indexOfObject: aTableView ];
	
	[self reloadAllData];
	
	return YES;
}

- (NSImage *)imageCellForPlayerColor:(int)playerColor {
	NSImage * image = [[NSImage alloc] initWithSize:NSMakeSize(32,32)];
	[image lockFocus];
	[[playerColors objectAtIndex:playerColor] set];
	NSRectFill( NSMakeRect(  0,0,32,32 ));
	[[NSColor blackColor] set];
	NSBezierPath * bp = [NSBezierPath bezierPathWithRect:NSMakeRect( 0,0,32,32) ];
	[bp setLineWidth:4.0];
	[bp stroke];
	[image unlockFocus];
	return image;
}

- (NSColor *)colorForPlayerIndex:(int)index {
	return [playerColors objectAtIndex:index];
}

- (int)playerNumberForTableView:(NSTableView *)aTableView rowIndex:(int)rowIndex { 
	int forceIndex = [tableViewArray indexOfObject: aTableView ];
	return [[[forceSetArray objectAtIndex:forceIndex] objectAtIndex:rowIndex] intValue];
}

@end
